import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:signage/app/data/models/cast_record_model.dart';
import 'package:signage/app/data/models/member_group_model.dart';
import 'package:signage/app/utils/sp_util.dart';

class CastRecordDetailController extends GetxController {
  //TODO: Implement CastRecordDetailController

  var groupList = [].obs;
  static const String GROUPS_KEY = 'member_groups';
  CastRecord? record;

  var currentGroup = Rxn<MemberGroup>();
  @override
  void onInit() {
    super.onInit();
    record = Get.arguments;
    print(record!.memberInfos!);
    initMemberSelection();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  // 加载保存的分组
  void loadGroups() {
    try {
      final savedGroups = SpUtil.getList(GROUPS_KEY);
      if (savedGroups != null) {
        print('存储的分组不为空');
        final List<dynamic> groupsJson = savedGroups;
        groupList.value =
            groupsJson.map((json) => MemberGroup.fromJson(json)).toList();
      }
    } catch (e) {
      print('加载分组失败: $e');
    }
  }

  void initMemberSelection() {
    if (Get.arguments != null) {
      final memberList = record?.memberInfos;
      final groupId = record?.groupId;
      // 先加载所有分组
      loadGroups();

      // 根据groupId查找对应分组
      if (groupId != null) {
        final targetGroup =
            groupList.firstWhereOrNull((group) => group.id == groupId);

        if (targetGroup != null) {
          currentGroup.value = targetGroup;
          currentGroup.value?.memberList = memberList;
          print('查看模式 - 设置成员列表 ${currentGroup.value?.memberList?.length}人');
        }
      }
    }
  }
}
